package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.config.NacosRuleConstants;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.SystemRuleEntity;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * packageName com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosRuleReceiver
 *
 * @author liudonghai
 * @version JDK 11
 * @date 2025/8/5
 * @description TODO
 */
@Component
public class NacosRuleReceiver {

    private static final Logger logger = LoggerFactory.getLogger(NacosRuleReceiver.class);

    @Value("${nacos.server-addr:${nacos.host:localhost:8848}}")
    private String serverAddr;

    // ... 其他依赖 ...

    private ConfigService configService;

    @PostConstruct
    public void init() throws Exception {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        configService = NacosFactory.createConfigService(properties);
    }
    // ... 其他规则获取方法 ...

    // 新增系统规则获取方法
    public List<SystemRuleEntity> getSystemRulesFromNacos(String app) {
        try {
            String dataId = NacosRuleConstants.getSystemDataId(app);
            String groupId = NacosRuleConstants.GROUP_ID;
            String content = configService.getConfig(dataId, groupId, 3000);
            if (StringUtil.isNotEmpty(content)) {
                return JSON.parseArray(content, SystemRuleEntity.class);
            }
        } catch (Exception e) {
            logger.error("Get system rules from Nacos failed", e);
        }
        return new ArrayList<>();
    }
    public List<ApiDefinitionEntity> getApiDefinitionsFromNacos(String app) {
        try {
            String dataId = NacosRuleConstants.getApiDefinitionDataId(app);
            String groupId = NacosRuleConstants.GROUP_ID;
            String content = configService.getConfig(dataId, groupId, 3000);
            if (StringUtil.isNotEmpty(content)) {
                return JSON.parseArray(content, ApiDefinitionEntity.class);
            }
        } catch (Exception e) {
            logger.error("Get API definitions from Nacos failed", e);
        }
        return new ArrayList<>();
    }
}
